#include "timer.h"

tmr_t tmrInit(void)
{
  tmr_t timer = {{0, 0}, {0, 0}, 0};

  return timer;
}

void tmrStart(tmr_t *timer)
{
  timer->accumulated = 0;
  scos_gettimeofday(&timer->started, NULL);
}

void tmrStop(tmr_t *timer)
{
  scos_gettimeofday(&timer->stopped, NULL);
}

double tmrGetValueInUs(const tmr_t *timer)
{
  time_t sec;
  suseconds_t usec;

  sec = timer->stopped.tv_sec - timer->started.tv_sec;
  usec = timer->stopped.tv_usec - timer->started.tv_usec;

  return (sec*(double)1000000.0)+usec + timer->accumulated;
}

void tmrSetValueInUs(tmr_t *timer, double value)
{
  timer->started.tv_sec = timer->started.tv_usec = 0;
  timer->stopped.tv_sec = value/1000000;
  timer->stopped.tv_usec = value-timer->stopped.tv_sec*1000000.0;
}

void tmrResume(tmr_t *timer)
{
  timer->accumulated = tmrGetValueInUs(timer);
  tmrStart(timer);
}
